package library.view;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import library.dao.Impl.BookDaoImpl;
import library.dao.Impl.BorrowHistoryDao;
import library.dao.Impl.UserDaoImpl;
import library.pojo.BorrowHistory;

public class BorrowDialog extends JDialog {
	private BorrowHistory bh;
	private JTextField userNameTextField;
	public static void main(String[] args) {
		new BorrowDialog(null);
	}
	public BorrowDialog(BorrowHistory bh) {
		ImageIcon icon = new ImageIcon(MainJTPane.class.getResource("/title.png"));
		this.setIconImage(icon.getImage());
		this.setTitle("借书");
		this.bh = bh;
		setBounds(100, 100, 400, 200);
		this.setLayout(null);
		
		JLabel message = new JLabel("请输入读者用户名:");
		message.setFont(new Font("宋体", Font.PLAIN, 18));
		message.setBounds(10, 30, 160, 18);
		this.add(message);
		
		JButton borrowButton = new JButton("借书");
		borrowButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				bookBorrowActionPerformed(e);
			}
		});
		borrowButton.setBounds(140, 100, 100, 30);
		this.add(borrowButton);
		
		userNameTextField = new JTextField();
		userNameTextField.setBounds(100,60, 230, 23);
		this.add(userNameTextField);
		userNameTextField.setColumns(10);
		
		
		this.setModal(true);
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		this.validate();
		
	}

	protected void bookBorrowActionPerformed(ActionEvent e) {
		String username = userNameTextField.getText();
		UserDaoImpl userDao = new UserDaoImpl();
		if(this.isEmpty(username)) {
			JOptionPane.showMessageDialog(null, "读者用户名不能为空！");
			return;
		}
		if(userDao.register(username)==null) {
			JOptionPane.showMessageDialog(null, "该用户不存在！");
			return;
		}
		BookDaoImpl bookDao = new BookDaoImpl();
		bookDao.updateStateBorrow(bh.getIsbn(),"借出");
		bh.setBorrowUser(username);
		BorrowHistoryDao bhDao;
		bhDao = new BorrowHistoryDao();
		bhDao.addBorrowHistory(bh);
		JOptionPane.showMessageDialog(null, "借书成功！");
		this.dispose();
		
	}
	/**
	 * 判断是否为空
	 */
	private boolean isEmpty(String str) {
		if(str==null || "".equals(str.trim())) {
			return true;
		}
		else {
			return false;
		}
	}
}
